package com.jlastu.dlxy_androidapp.view.main;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.transition.Slide;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.jlastu.dlxy_androidapp.R;
import com.jlastu.dlxy_androidapp.adapter.GoodsPhotoAdapter;
import com.jlastu.dlxy_androidapp.contract.AddGoodsContract;
import com.jlastu.dlxy_androidapp.entity.Goods;
import com.jlastu.dlxy_androidapp.entity.Photo;
import com.jlastu.dlxy_androidapp.presenter.AddGoodsPresenter;
import com.jlastu.dlxy_androidapp.utils.SpUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AddGoodsActivity extends AppCompatActivity implements
        GoodsPhotoAdapter.OnPhotoListener, AddGoodsContract.IAddGoodsView, View.OnClickListener {
    private SpUtils mSpUtils;

    private RecyclerView mPhotoRecyclerView;
    private EditText mGoodsNameEdit;

    private EditText mGoodsPriceEdit;

    private ImageView mBack;
    private Button mSendButton;
    private List<Photo> mPhotoList;
    private GoodsPhotoAdapter mGoodsPhotoAdapter;
    private ActivityResultLauncher mActivityResultLauncher;
    private AddGoodsContract.IAddGoodsPresenter mAddGoodsPresenter;

    private ImageButton mGoodsClassify;

    private RadioGroup mClassify;
    private RadioButton mRadioButton_1;
    private RadioButton mRadioButton_2;
    private RadioButton mRadioButton_3;

    private ImageButton mGoodsUnit;
    private RadioGroup mUnit;
    private RadioButton mRadioButton_4;
    private RadioButton mRadioButton_5;
    private RadioButton mRadioButton_6;

    private EditText mGoodsMainEdit;

    private final String TAG = "MainActivity";

    public class MainActivity extends AppCompatActivity {

        @Override
        public void onConfigurationChanged(android.content.res.Configuration newConfig) {
            super.onConfigurationChanged(newConfig);

            // 检查屏幕方向是否为横屏
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Log.d("Orientation", "Landscape detected");

                // 创建并启动新的Activity
                Intent intent = new Intent(this, LandscapeActivity.class);
                startActivity(intent);

                // 可选：关闭当前Activity
                finish();
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setEnterTransition(new Slide());
        setContentView(R.layout.activity_add_goods);
        mAddGoodsPresenter = new AddGoodsPresenter(this, this);
        mPhotoList = new ArrayList<>();
        mPhotoList.add(new Photo());
        mPhotoRecyclerView = findViewById(R.id.rv_goods_photo);
        mGoodsNameEdit = findViewById(R.id.et_goods_name);
        mGoodsPriceEdit = findViewById(R.id.danjia_ed);
        mSendButton = findViewById(R.id.goods_send);
        mSendButton.setOnClickListener(this);
        mGoodsClassify = findViewById(R.id.arrow_icon);
        mGoodsClassify.setOnClickListener(this);
        mClassify = findViewById(R.id.radioGroup);
        mRadioButton_1 = findViewById(R.id.radioButtonVegetables);
        mRadioButton_2 = findViewById(R.id.radioButtonMeatEgg);
        mRadioButton_3 = findViewById(R.id.radioButtonRiceNoodles);
        mGoodsUnit = findViewById(R.id.arrow_unit);
        mGoodsUnit.setOnClickListener(this);
        mUnit = findViewById(R.id.radioGroup_unit);
        mRadioButton_4 = findViewById(R.id.radioButtonKG);
        mRadioButton_5 = findViewById(R.id.radioButtonAXE);
        mRadioButton_6 = findViewById(R.id.radioButtonLIANG);
        mGoodsMainEdit = findViewById(R.id.main_ed);
        mBack = findViewById(R.id.back);
        mBack.setOnClickListener(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mPhotoRecyclerView.setLayoutManager(gridLayoutManager);
        mGoodsPhotoAdapter = new GoodsPhotoAdapter(mPhotoList);
        mGoodsPhotoAdapter.setPhotoListener(this);
        mPhotoRecyclerView.setAdapter(mGoodsPhotoAdapter);
        mSpUtils = new SpUtils(getApplicationContext());
        onActivityResult();

        mClassify.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radioButtonVegetables) {
                    // 蔬菜水果被选中
                    RadioButton selectedRadioButton = mClassify.findViewById(mClassify.getCheckedRadioButtonId());
                    String selectedOption = selectedRadioButton.getText().toString();
                    Log.d(TAG, "onCheckedChanged: " + mClassify.getCheckedRadioButtonId());
                    Log.d(TAG, "文本: " + selectedOption);

                } else if (checkedId == R.id.radioButtonMeatEgg) {
                    // 禽畜肉蛋被选中
                    RadioButton selectedRadioButton = mClassify.findViewById(mClassify.getCheckedRadioButtonId());
                    String selectedOption = selectedRadioButton.getText().toString();
                    Log.d(TAG, "onCheckedChanged: " + mClassify.getCheckedRadioButtonId());
                    Log.d(TAG, "文本: " + selectedOption);
                } else if (checkedId == R.id.radioButtonRiceNoodles) {
                    // 米面粮油被选中
                    RadioButton selectedRadioButton = mClassify.findViewById(mClassify.getCheckedRadioButtonId());
                    String selectedOption = selectedRadioButton.getText().toString();
                    Log.d(TAG, "onCheckedChanged: " + mClassify.getCheckedRadioButtonId());
                    Log.d(TAG, "文本: " + selectedOption);
                }
            }
        });
        mUnit.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radioButtonKG) {
                    // 公斤被选中
                    RadioButton selectedRadioButton = mUnit.findViewById(mUnit.getCheckedRadioButtonId());
                    String selectedOption = selectedRadioButton.getText().toString();
                    Log.d(TAG, "onCheckedChanged: " + mUnit.getCheckedRadioButtonId());
                    Log.d(TAG, "文本: " + selectedOption);

                } else if (checkedId == R.id.radioButtonAXE) {
                    // 斤被选中
                    RadioButton selectedRadioButton = mUnit.findViewById(mUnit.getCheckedRadioButtonId());
                    String selectedOption = selectedRadioButton.getText().toString();
                    Log.d(TAG, "onCheckedChanged: " + mUnit.getCheckedRadioButtonId());
                    Log.d(TAG, "文本: " + selectedOption);
                } else if (checkedId == R.id.radioButtonLIANG) {
                    // 两被选中
                    RadioButton selectedRadioButton = mUnit.findViewById(mUnit.getCheckedRadioButtonId());
                    String selectedOption = selectedRadioButton.getText().toString();
                    Log.d(TAG, "onCheckedChanged: " + mUnit.getCheckedRadioButtonId());
                    Log.d(TAG, "文本: " + selectedOption);
                }
            }
        });


    }

    @Override
    public void onAdd() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        mActivityResultLauncher.launch(intent);
    }

    @Override
    public void onDelete(int position) {
        //暂时没用
    }

    private void onActivityResult() {
        mActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        int resultCode = result.getResultCode();
                        if (resultCode == RESULT_OK) {
                            Intent data = result.getData();
                            Uri selectedImageUri = data.getData();
                            try {
                                // 使用图片URI进行处理，例如加载到ImageView中
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                                Photo photo = new Photo();
                                photo.setBitmap(bitmap);
                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                Bitmap resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * 0.5), (int) (bitmap.getHeight() * 0.5), true);
                                resized.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                photo.setData(outputStream.toByteArray());
                                mGoodsPhotoAdapter.addPhoto(photo);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    public void showGoodsList(List<Goods> goodsList) {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            onBackPressed();
            finish();
        } else if (id == R.id.goods_send) {
            RadioButton selectedRadioButton = mClassify.findViewById(mClassify.getCheckedRadioButtonId());
            String selectedOption = (selectedRadioButton != null) ? selectedRadioButton.getText().toString().trim() : "";
            RadioButton selectedRadioButton_Unit = mUnit.findViewById(mUnit.getCheckedRadioButtonId());
            String selectedOption_Unit = (selectedRadioButton_Unit != null) ? selectedRadioButton_Unit.getText().toString().trim() : "";

            if (mGoodsNameEdit.getText().toString().isEmpty()) {
                Toast.makeText(this, "请填写货品名称", Toast.LENGTH_SHORT).show();
            } else if (mGoodsPhotoAdapter.getPhotoList().isEmpty()) {
                Toast.makeText(this, "请添加商品图片", Toast.LENGTH_SHORT).show();
            } else if (selectedOption.isEmpty()) {
                Toast.makeText(this, "请选择商品分类", Toast.LENGTH_SHORT).show();
            } else if (selectedOption_Unit.isEmpty()) {
                Toast.makeText(this, "请选择商品单位", Toast.LENGTH_SHORT).show();
            } else if (mGoodsPriceEdit.getText().toString().isEmpty()) {
                Toast.makeText(this, "请填写商品价格", Toast.LENGTH_SHORT).show();
            } else if (mGoodsMainEdit.getText().toString().isEmpty()) {
                Toast.makeText(this, "请填写商品详情", Toast.LENGTH_SHORT).show();
            } else {

                Goods goods = new Goods();
                goods.setStore_id(mSpUtils.getInt("userid",0));
                goods.setName(mGoodsNameEdit.getText().toString());
                goods.setPrice(Double.parseDouble(mGoodsPriceEdit.getText().toString()));
                goods.setUnit(selectedOption_Unit);
                goods.setMessage(mGoodsMainEdit.getText().toString());
                goods.setClassify(selectedOption);
                goods.setPhotoList(mGoodsPhotoAdapter.getPhotoList());
                mAddGoodsPresenter.saveGoods(goods);
                Toast.makeText(this, "发布成功！", Toast.LENGTH_SHORT).show();
                onBackPressed();
            }
        } else if (id == R.id.arrow_icon) {
            if (mClassify.getVisibility() == View.GONE) {
                mClassify.setVisibility(View.VISIBLE);
            } else {
                mClassify.setVisibility(View.GONE);
            }
        } else if (id == R.id.arrow_unit) {
            if (mUnit.getVisibility() == View.GONE) {
                mUnit.setVisibility(View.VISIBLE);
            } else {
                mUnit.setVisibility(View.GONE);
            }
        }
    }
}
